package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Notice;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.NoticeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void save(Notice notice) {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        notice.setIssuer(employee);
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        notice.setPubdate(new Date());
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    // 往中间表插入一条信息
    @Override
    public void saveNoticeEmployee(Long id) {
        boolean flag = false;
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if (noticeMapper.selectNoticeIdAndEmployeeId(id,employee.getId())>0) {
            flag = false;
            return;
        }else {
            noticeMapper.saveNoticeEmployee(id,employee.getId());
            flag = true;
        }
    }
}
